/**
 * 
 */
package com.antilia.infomaresme.pages.details.message;

import javax.mail.MessagingException;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;

import com.antilia.infomaresme.InfomaresmeApplication;
import com.antilia.infomaresme.data.dataobjects.Item;
import com.antilia.infomaresme.data.dataobjects.User;
import com.antilia.infomaresme.data.dataobjects.UserMessage;
import com.antilia.infomaresme.form.ShinyForm;
import com.antilia.infomaresme.mail.MailUtil;

/**
 * @author Ernesto
 *
 */
public abstract class UserMessagePanel extends Panel {

	private static final long serialVersionUID = 1L;

	private UserMessage message;
	
	private FeedbackPanel feedback;
	
	private Form<UserMessage> form;
	/**
	 * @param id
	 */
	public UserMessagePanel(String id, final IModel<Item> model) {
		super(id, model);
		message = new UserMessage();
		message.setItem(model.getObject());
		message.setUser(model.getObject().getAuthor());
		form = new ShinyForm<UserMessage>("form", new CompoundPropertyModel<UserMessage>(message));
		form.setOutputMarkupId(true);
		form.add(new TextField<String>("subject").setRequired(true));
		form.add(new TextArea<String>("text").setRequired(true));
		add(form);
		AjaxSubmitLink link = new AjaxSubmitLink("link") {
			
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
				User author = model.getObject().getAuthor();
				try {
					//TODO persist message on database
					InfomaresmeApplication.getQAApplication().getUserMessagesDao().save(message);
					MailUtil.sendEmail(author.getEmail(), message.getSubject(), message.getText());
				} catch (MessagingException e) {
					//TODO fix this an add login
					e.printStackTrace();
				}
				UserMessagePanel.this.onSend(target, message);
			}
			
			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				target.add(form);
			}
		};
		form.add(link);
		
		add(feedback=new FeedbackPanel("feedback"));
		feedback.setOutputMarkupId(true);
	}
	
	protected abstract void onSend(AjaxRequestTarget target, UserMessage message);

}
